package com.resource.error;

import com.alibaba.fastjson.JSON;
import com.resource.exception.AuthenticationCustomException;
import com.utility.constant.HttpConstant;
import com.utility.result.Result;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 匿名访问统一回调
 * @author: hw
 * @date: 2020/12/10 15:57
 */
@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Value("Authorization Header头部信息异常，token失效或者为空")
    private String insufficientAuthenticationException;

    @Value("自定义异常")
    private String authenticationCustomException;

    @Value("用户登录时身份认证失败.")
    private String badCredentialsException;

    @Value("用户token无效.")
    private String exception;

    @Value("token无效")
    private String token;

    @SneakyThrows
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e){
        //设置缓存区编码为UTF-8编码格式
        response.setCharacterEncoding(HttpConstant.UTF8);
        //在响应中主动告诉浏览器使用UTF-8编码格式来接收数据
        response.setHeader(HttpConstant.CONTENT_TYPE, HttpConstant.REQUEST_HOST_JSON);
        // 用户登录时身份认证未通过
        if (e instanceof BadCredentialsException) {
            log.error(badCredentialsException);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(JSON.toJSONString(Result.returnCode(-1,token)));
        } else if (e instanceof InsufficientAuthenticationException) {
            e.printStackTrace();
            log.error(insufficientAuthenticationException);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(JSON.toJSONString(Result.returnCode(-1,token)));
        } else if (e instanceof AuthenticationCustomException) {
            log.error(authenticationCustomException);
            response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
            response.getWriter().write(JSON.toJSONString(Result.returnCode(-1,e.getMessage())));
        }
        else {
            log.info(exception);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(JSON.toJSONString(Result.returnCode(-1,token)));
        }
    }
}
